package com.example.demo.service.impl;

import com.example.demo.dto.MultipleApprovalResultDTO;
import com.example.demo.dto.TaskApprovalStatusDTO;
import com.example.demo.entity.*;
import com.example.demo.mapper.*;
import com.example.demo.service.*;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.ArrayList;

@Service
public class TaskRoutingServiceImpl implements TaskRoutingService {

    @Autowired
    private TaskApprovalStatusMapper taskApprovalStatusMapper;

    @Autowired
    private NewTaskMapper newTaskMapper;

    @Autowired
    private ProcessNodeMapper processNodeMapper;

    @Autowired
    private RoleDepartmentUserMapper roleDepartmentUserMapper;

    @Autowired
    private RoutingRuleMapper routingRuleMapper;

    @Autowired
    private TaskApprovalStatusService taskApprovalStatusService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    // 匹配过程类
    private static class MatchingProcess {
        private List<String> routingRules = new ArrayList<>();
        private List<String> matchingDetails = new ArrayList<>();
        private String finalResult;
        private String reason;

        public void addRoutingRule(String rule) {
            routingRules.add(rule);
        }

        public void addMatchingDetail(String detail) {
            matchingDetails.add(detail);
        }

        public void setFinalResult(String result, String reason) {
            this.finalResult = result;
            this.reason = reason;
        }

        public List<String> getRoutingRules() { return routingRules; }
        public List<String> getMatchingDetails() { return matchingDetails; }
        public String getFinalResult() { return finalResult; }
        public String getReason() { return reason; }
    }

    // 日志文件路径
    private static final String LOG_DIR = "logs/routing";
    private static final String LOG_FILE_PREFIX = "task_routing_";
    private static final DateTimeFormatter FILE_DATE_FORMAT = DateTimeFormatter.ofPattern("yyyyMMdd");
    private static final DateTimeFormatter LOG_TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    @Transactional
    public TaskApprovalStatusDTO assignApprover(Long taskApprovalStatusId) {
        //log.info("开始为任务审批状态ID: {} 分配审批人", taskApprovalStatusId);

        // 1. 获取任务审批状态信息
        TaskApprovalStatus approvalStatus = taskApprovalStatusMapper.selectById(taskApprovalStatusId);
        if (approvalStatus == null) {
            //log.error("任务审批状态不存在，ID: {}", taskApprovalStatusId);
            throw new RuntimeException("任务审批状态不存在");
        }

        //log.info("任务审批状态信息: TaskID={}, FlowID={}, NodeID={}",
//                approvalStatus.getTaskId(), approvalStatus.getFlowId(), approvalStatus.getNodeId());

        // 2. 获取任务详细数据
        NewTask task = newTaskMapper.selectById(approvalStatus.getTaskId());
        if (task == null) {
            //log.error("任务不存在，TaskID: {}", approvalStatus.getTaskId());
            throw new RuntimeException("任务不存在");
        }

        //log.info("任务数据: BizUniqueId={}, DataSourceId={}, RawData长度={}",
//                task.getBizUniqueId(), task.getDataSourceId(),
//                task.getRawData() != null ? task.getRawData().length() : 0);

        // 3. 获取流程节点信息
        ProcessNode processNode = processNodeMapper.selectById(approvalStatus.getNodeId());
        if (processNode == null) {
            //log.error("流程节点不存在，NodeID: {}", approvalStatus.getNodeId());
            throw new RuntimeException("流程节点不存在");
        }

        //log.info("流程节点信息: NodeName={}, Department={}, Role={}, DepartmentId={}, RoleId={}",
//                processNode.getNodeName(), processNode.getDepartment(), processNode.getRole(),
//                processNode.getDepartmentId(), processNode.getRoleId());

        // 4. 解析任务原始数据
        JsonNode taskDataJson = null;
        try {
            if (task.getRawData() != null && !task.getRawData().trim().isEmpty()) {
                taskDataJson = objectMapper.readTree(task.getRawData());
                //log.info("成功解析任务原始数据，字段数量: {}", taskDataJson.size());
            } else {
                //log.warn("任务原始数据为空或无效");
            }
        } catch (Exception e) {
            //log.error("解析任务原始数据失败: {}", e.getMessage(), e);
        }

        // 5. 创建匹配过程记录器
        MatchingProcess matchingProcess = new MatchingProcess();

        // 6. 查找默认处理人（从RoleDepartmentUser表）
        String defaultApproverInfo = findDefaultApprover(processNode.getRoleId(), processNode.getDepartmentId());
        //log.info("默认处理人信息: {}", defaultApproverInfo);
        matchingProcess.addMatchingDetail("默认处理人查询结果: " + (defaultApproverInfo != null ? defaultApproverInfo : "未找到默认处理人"));

        // 7. 查找路由规则匹配的处理人
        String routingApproverInfo = findRoutingApproverWithProcess(processNode.getRoleId(), processNode.getDepartmentId(), taskDataJson, matchingProcess);
        //log.info("路由规则匹配的处理人信息: {}", routingApproverInfo);

        // 8. 确定最终的审批人（优先使用路由规则匹配的，否则使用默认的）
        String finalApproverInfo;
        if (routingApproverInfo != null) {
            finalApproverInfo = routingApproverInfo;
            matchingProcess.setFinalResult(finalApproverInfo, "使用路由规则匹配的审批人");
        } else {
            finalApproverInfo = defaultApproverInfo;
            matchingProcess.setFinalResult(finalApproverInfo, "路由规则无法匹配，使用默认审批人");
        }
        //log.info("最终确定的审批人信息: {}", finalApproverInfo);

        // 9. 将所有路由信息写入日志文件
        writeRoutingInfoToFile(taskApprovalStatusId, approvalStatus, task, processNode, taskDataJson,
                defaultApproverInfo, routingApproverInfo, finalApproverInfo, matchingProcess);

        // 9. 解析审批人信息并更新审批状态
        if (finalApproverInfo != null) {
            updateApprovalStatusWithApprover(approvalStatus, finalApproverInfo);
        } else {
            //log.warn("未找到合适的审批人，保持原状态");
        }

        // 10. 返回更新后的审批状态
        return taskApprovalStatusService.getTaskApprovalStatusById(taskApprovalStatusId);
    }

    @Override
    @Transactional
    public MultipleApprovalResultDTO assignMultipleApprovers(Long taskApprovalStatusId) {
        //log.info("开始为任务审批状态ID: {} 分配多个审批人并根据负载均衡选择", taskApprovalStatusId);

        // 创建返回对象
        MultipleApprovalResultDTO resultDTO = new MultipleApprovalResultDTO();

        // 1. 获取任务审批状态信息
        TaskApprovalStatus approvalStatus = taskApprovalStatusMapper.selectById(taskApprovalStatusId);
        if (approvalStatus == null) {
            //log.error("任务审批状态不存在，ID: {}", taskApprovalStatusId);
            throw new RuntimeException("任务审批状态不存在");
        }

        // 设置原始任务审批状态信息
        TaskApprovalStatusDTO originalDTO = new TaskApprovalStatusDTO();
        originalDTO.setId(approvalStatus.getId());
        originalDTO.setTaskFlowId(approvalStatus.getTaskFlowId());
        originalDTO.setNodeId(approvalStatus.getNodeId());
        originalDTO.setStatus(approvalStatus.getStatus());
        originalDTO.setApproverId(approvalStatus.getApproverId());
        originalDTO.setApproverName(approvalStatus.getApproverName());
        originalDTO.setTaskId(approvalStatus.getTaskId());
        originalDTO.setDataSourceId(approvalStatus.getDataSourceId());
        originalDTO.setFlowId(approvalStatus.getFlowId());
        resultDTO.setOriginalTaskApprovalStatus(originalDTO);

        //log.info("任务审批状态信息: TaskID={}, FlowID={}, NodeID={}",
//                approvalStatus.getTaskId(), approvalStatus.getFlowId(), approvalStatus.getNodeId());

        // 2. 获取任务详细数据
        NewTask task = newTaskMapper.selectById(approvalStatus.getTaskId());
        if (task == null) {
            //log.error("任务不存在，TaskID: {}", approvalStatus.getTaskId());
            throw new RuntimeException("任务不存在");
        }

//        //log.info("任务数据: BizUniqueId={}, DataSourceId={}, RawData长度={}",
//                task.getBizUniqueId(), task.getDataSourceId(),
//                task.getRawData() != null ? task.getRawData().length() : 0);

        // 3. 获取流程节点信息
        ProcessNode processNode = processNodeMapper.selectById(approvalStatus.getNodeId());
        if (processNode == null) {
            //log.error("流程节点不存在，NodeID: {}", approvalStatus.getNodeId());
            throw new RuntimeException("流程节点不存在");
        }
//
//        //log.info("流程节点信息: NodeName={}, Department={}, Role={}, DepartmentId={}, RoleId={}",
//                processNode.getNodeName(), processNode.getDepartment(), processNode.getRole(),
//                processNode.getDepartmentId(), processNode.getRoleId());

        // 4. 解析任务原始数据
        JsonNode taskDataJson = null;
        try {
            if (task.getRawData() != null && !task.getRawData().trim().isEmpty()) {
                taskDataJson = objectMapper.readTree(task.getRawData());
                //log.info("成功解析任务原始数据，字段数量: {}", taskDataJson.size());
            } else {
                //log.warn("任务原始数据为空或无效");
            }
        } catch (Exception e) {
            //log.error("解析任务原始数据失败: {}", e.getMessage(), e);
        }

        // 5. 创建匹配过程记录器
        MatchingProcess matchingProcess = new MatchingProcess();

        // 6. 查找默认处理人（从RoleDepartmentUser表）
        String defaultApproverInfo = findDefaultApprover(processNode.getRoleId(), processNode.getDepartmentId());
        //log.info("默认处理人信息: {}", defaultApproverInfo);
        matchingProcess.addMatchingDetail("默认处理人查询结果: " + (defaultApproverInfo != null ? defaultApproverInfo : "未找到默认处理人"));

        // 7. 查找路由规则匹配的处理人
        String routingApproverInfo = findRoutingApproverWithProcess(processNode.getRoleId(), processNode.getDepartmentId(), taskDataJson, matchingProcess);
        //log.info("路由规则匹配的处理人信息: {}", routingApproverInfo);

        // 8. 解析匹配到的所有审批人
        List<MultipleApprovalResultDTO.ApproverInfoDTO> matchedApprovers = parseAllApprovers(routingApproverInfo, defaultApproverInfo);
        resultDTO.setMatchedApprovers(matchedApprovers);

        // 9. 根据负载均衡选择最合适的审批人
        MultipleApprovalResultDTO.ApproverInfoDTO selectedApprover = selectApproverByLoadBalancing(matchedApprovers);
        resultDTO.setSelectedApprover(selectedApprover);
        resultDTO.setSelectionStrategy("负载均衡选择");

        // 10. 获取审批人负载信息
        List<MultipleApprovalResultDTO.ApproverLoadInfoDTO> loadInfoList = getApproverLoadInfo(matchedApprovers);
        resultDTO.setApproverLoadInfoList(loadInfoList);

        // 11. 更新审批状态
        if (selectedApprover != null) {
            updateApprovalStatusWithSelectedApprover(approvalStatus, selectedApprover);
        } else {
            //log.warn("未找到合适的审批人，保持原状态");
        }

        //log.info("多审批人分配完成，匹配到 {} 个审批人，选择审批人ID: {}",
//                matchedApprovers.size(), selectedApprover != null ? selectedApprover.getUserId() : "无");

        return resultDTO;
    }

    @Override
    @Transactional
    public int batchAssignApprovers(Long taskFlowId) {
        try {
            //log.info("开始批量分配审批人，任务流程ID: {}", taskFlowId);

            // 查询该流程下的所有待审批状态
            List<TaskApprovalStatus> approvalStatuses = taskApprovalStatusMapper.selectByTaskFlowId(taskFlowId);

            int successCount = 0;
            for (TaskApprovalStatus status : approvalStatuses) {
                try {
                    assignApprover(status.getId());
                    successCount++;
                } catch (Exception e) {
                    //log.error("分配审批人失败，审批状态ID: {}", status.getId(), e);
                }
            }

            //log.info("批量分配审批人完成，成功: {}, 总数: {}", successCount, approvalStatuses.size());
            return successCount;
        } catch (Exception e) {
            //log.error("批量分配审批人失败，任务流程ID: {}", taskFlowId, e);
            return 0;
        }
    }

    @Override
    @Transactional
    public int batchAssignApproversByDataSource(Long dataSourceId) {
        try {
            //log.info("开始按数据源批量分配审批人，数据源ID: {}", dataSourceId);

            // 查询该数据源下的所有待审批状态
            List<TaskApprovalStatus> approvalStatuses = taskApprovalStatusMapper.selectByDataSourceId(dataSourceId);

            int successCount = 0;
            for (TaskApprovalStatus status : approvalStatuses) {
                try {
                    assignApprover(status.getId());
                    successCount++;
                } catch (Exception e) {
                    //log.error("分配审批人失败，审批状态ID: {}", status.getId(), e);
                }
            }

            //log.info("按数据源批量分配审批人完成，成功: {}, 总数: {}", successCount, approvalStatuses.size());
            return successCount;
        } catch (Exception e) {
            //log.error("按数据源批量分配审批人失败，数据源ID: {}", dataSourceId, e);
            return 0;
        }
    }

    /**
     * 查找默认处理人
     */
    private String findDefaultApprover(Long roleId, Long departmentId) {
        //log.info("查找默认处理人: RoleId={}, DepartmentId={}", roleId, departmentId);

        if (roleId == null || departmentId == null) {
            //log.warn("角色ID或部门ID为空，无法查找默认处理人");
            return null;
        }

        try {
            // 查询RoleDepartmentUser表中的默认处理人
            List<RoleDepartmentUser> defaultUsers = roleDepartmentUserMapper.selectByRoleAndDepartment(roleId.intValue(), departmentId.intValue());

            if (defaultUsers != null && !defaultUsers.isEmpty()) {
                // 优先选择标记为默认的用户
                RoleDepartmentUser defaultUser = defaultUsers.stream()
                        .filter(user -> Boolean.TRUE.equals(user.getIsDefault()))
                        .findFirst()
                        .orElse(defaultUsers.get(0)); // 如果没有标记为默认的，选择第一个

                // 返回JSON格式的审批人信息，与路由规则匹配结果保持一致
                String approverInfo = String.format(
                        "{\"primaryUser\": {\"id\": %d, \"name\": \"%s\", \"authId\": \"%s\"}}",
                        defaultUser.getUserId(),
                        defaultUser.getUserName() != null ? defaultUser.getUserName().replace("\"", "\\\"") : "",
                        defaultUser.getUserAuthid() != null ? defaultUser.getUserAuthid() : "");

                //log.info("找到默认处理人: {}", approverInfo);
                return approverInfo;
            } else {
                //log.warn("未找到角色ID: {} 和部门ID: {} 的默认处理人", roleId, departmentId);
                return null;
            }
        } catch (Exception e) {
            //log.error("查找默认处理人失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 查找路由规则匹配的处理人（带匹配过程记录）
     * 使用逐步删除字段的匹配策略：如果完整匹配失败，则逐步删除最后一个字段继续匹配
     */
    private String findRoutingApproverWithProcess(Long roleId, Long departmentId, JsonNode taskDataJson, MatchingProcess matchingProcess) {
        //log.info("开始查找路由规则匹配的处理人: RoleId={}, DepartmentId={}", roleId, departmentId);
        matchingProcess.addMatchingDetail("开始路由规则匹配，角色ID: " + roleId + ", 部门ID: " + departmentId);

        if (roleId == null || departmentId == null) {
            //log.warn("角色ID或部门ID为空，无法查找路由规则");
            matchingProcess.addMatchingDetail("角色ID或部门ID为空，无法查找路由规则");
            return null;
        }

        try {
            // 查询该角色和部门的路由规则
            List<RoutingRule> routingRules = routingRuleMapper.selectByRoleAndDepartment(roleId.intValue(), departmentId.intValue());

            if (routingRules == null || routingRules.isEmpty()) {
                //log.info("未找到角色ID: {} 和部门ID: {} 的路由规则", roleId, departmentId);
                matchingProcess.addMatchingDetail("未找到任何路由规则");
                return null;
            }

            //log.info("找到 {} 个路由规则，开始逐个检查匹配", routingRules.size());
            matchingProcess.addMatchingDetail("找到 " + routingRules.size() + " 个路由规则");

            // 遍历路由规则，使用逐步删除字段的匹配策略
            for (int i = 0; i < routingRules.size(); i++) {
                RoutingRule rule = routingRules.get(i);
                //log.info("========== 开始检查路由规则ID: {} ==========", rule.getId());
                //log.info("原始路由规则FieldValues: {}", rule.getFieldValues());
                matchingProcess.addRoutingRule("规则" + (i+1) + " [ID:" + rule.getId() + "] 字段值: " + rule.getFieldValues());

                String matchedApprover = tryMatchWithFieldReductionAndProcess(rule, taskDataJson, matchingProcess, i+1);
                if (matchedApprover != null) {
                    //log.info("路由规则ID: {} 匹配成功，返回审批人: {}", rule.getId(), matchedApprover);
                    matchingProcess.addMatchingDetail("规则" + (i+1) + " 匹配成功，返回审批人: " + matchedApprover);
                    return matchedApprover;
                }

                //log.info("========== 路由规则ID: {} 匹配失败 ==========", rule.getId());
                matchingProcess.addMatchingDetail("规则" + (i+1) + " 匹配失败");
            }

            //log.info("所有路由规则都无法匹配任务数据，将使用默认负责人");
            matchingProcess.addMatchingDetail("所有路由规则都无法匹配任务数据");
            return null;
        } catch (Exception e) {
            //log.error("查找路由规则匹配的处理人失败: {}", e.getMessage(), e);
            matchingProcess.addMatchingDetail("匹配过程中发生异常: " + e.getMessage());
            return null;
        }
    }

    /**
     * 查找路由规则匹配的处理人
     * 使用逐步删除字段的匹配策略：如果完整匹配失败，则逐步删除最后一个字段继续匹配
     */
    private String findRoutingApprover(Long roleId, Long departmentId, JsonNode taskDataJson) {
        //log.info("开始查找路由规则匹配的处理人: RoleId={}, DepartmentId={}", roleId, departmentId);

        if (roleId == null || departmentId == null) {
            //log.warn("角色ID或部门ID为空，无法查找路由规则");
            return null;
        }

        try {
            // 查询该角色和部门的路由规则
            List<RoutingRule> routingRules = routingRuleMapper.selectByRoleAndDepartment(roleId.intValue(), departmentId.intValue());

            if (routingRules == null || routingRules.isEmpty()) {
                //log.info("未找到角色ID: {} 和部门ID: {} 的路由规则", roleId, departmentId);
                return null;
            }

            //log.info("找到 {} 个路由规则，开始逐个检查匹配", routingRules.size());

            // 遍历路由规则，使用逐步删除字段的匹配策略
            for (RoutingRule rule : routingRules) {
                //log.info("========== 开始检查路由规则ID: {} ==========", rule.getId());
                //log.info("原始路由规则FieldValues: {}", rule.getFieldValues());

                String matchedApprover = tryMatchWithFieldReduction(rule, taskDataJson);
                if (matchedApprover != null) {
                    //log.info("路由规则ID: {} 匹配成功，返回审批人: {}", rule.getId(), matchedApprover);
                    return matchedApprover;
                }

                //log.info("========== 路由规则ID: {} 匹配失败 ==========", rule.getId());
            }

            //log.info("所有路由规则都无法匹配任务数据，将使用默认负责人");
            return null;
        } catch (Exception e) {
            //log.error("查找路由规则匹配的处理人失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 使用逐步删除字段的策略尝试匹配路由规则（带匹配过程记录）
     * 如果完整匹配失败，则逐步删除最后一个字段继续匹配，直到只剩一个字段仍无法匹配为止
     */
    private String tryMatchWithFieldReductionAndProcess(RoutingRule rule, JsonNode taskDataJson, MatchingProcess matchingProcess, int ruleIndex) {
        if (rule.getFieldValues() == null || rule.getFieldValues().trim().isEmpty()) {
            //log.warn("路由规则ID: {} 的fieldValues为空，跳过匹配", rule.getId());
            matchingProcess.addMatchingDetail("规则" + ruleIndex + " 的fieldValues为空，跳过匹配");
            return null;
        }

        if (taskDataJson == null) {
            //log.warn("任务数据为空，无法匹配路由规则ID: {}", rule.getId());
            matchingProcess.addMatchingDetail("规则" + ruleIndex + " 任务数据为空，无法匹配");
            return null;
        }

        try {
            // 解析路由规则的字段值
            JsonNode originalRuleFields = objectMapper.readTree(rule.getFieldValues());
            //log.info("开始匹配路由规则ID: {}，原始字段数量: {}", rule.getId(), originalRuleFields.size());
            matchingProcess.addMatchingDetail("规则" + ruleIndex + " 开始匹配，原始字段数量: " + originalRuleFields.size());

            // 将字段转换为列表，便于逐步删除
            java.util.List<String> fieldNames = new java.util.ArrayList<>();
            originalRuleFields.fieldNames().forEachRemaining(fieldNames::add);

            // 从完整字段开始，逐步删除最后一个字段进行匹配
            for (int fieldCount = fieldNames.size(); fieldCount >= 1; fieldCount--) {
                // 构建当前要匹配的字段集合
                java.util.List<String> currentFields = fieldNames.subList(0, fieldCount);

                //log.info("--- 尝试匹配 {} 个字段: {} ---", fieldCount, currentFields);
                matchingProcess.addMatchingDetail("规则" + ruleIndex + " 尝试匹配 " + fieldCount + " 个字段: " + currentFields);

                // 检查当前字段集合是否匹配
                boolean allMatched = true;
                StringBuilder matchLog = new StringBuilder();
//                match//log.append("字段匹配详情:\n");

                for (String fieldName : currentFields) {
                    JsonNode ruleValue = originalRuleFields.get(fieldName);
                    JsonNode taskValue = taskDataJson.get(fieldName);

                    String ruleValueStr = ruleValue != null ? ruleValue.asText() : "null";
                    String taskValueStr = taskValue != null ? taskValue.asText() : "null";

                    boolean fieldMatched = taskValue != null && ruleValueStr.equals(taskValueStr);

                    String fieldMatchDetail = String.format("  字段[%s]: 规则值=%s, 任务值=%s, 匹配=%s",
                            fieldName, ruleValueStr, taskValueStr, fieldMatched ? "✓" : "✗");
//                    match//log.append(fieldMatchDetail).append("\n");
                    matchingProcess.addMatchingDetail("规则" + ruleIndex + " " + fieldMatchDetail);

                    if (!fieldMatched) {
                        allMatched = false;
                    }
                }

                //log.info(match//log.toString());

                if (allMatched) {
                    //log.info("*** 匹配成功！使用 {} 个字段匹配成功 ***", fieldCount);
                    String successMsg = "规则" + ruleIndex + " 匹配成功！使用 " + fieldCount + " 个字段匹配成功";
                    matchingProcess.addMatchingDetail(successMsg);
                    if (fieldCount < fieldNames.size()) {
                        String reductionMsg = "注意：通过删除 " + (fieldNames.size() - fieldCount) + " 个字段后匹配成功，删除的字段: " +
                                fieldNames.subList(fieldCount, fieldNames.size());
                        //log.info(reductionMsg);
                        matchingProcess.addMatchingDetail("规则" + ruleIndex + " " + reductionMsg);
                    }
                    return rule.getAssignedUsers();
                } else {
                    //log.info("使用 {} 个字段匹配失败", fieldCount);
                    matchingProcess.addMatchingDetail("规则" + ruleIndex + " 使用 " + fieldCount + " 个字段匹配失败");
                    if (fieldCount > 1) {
                        String nextMsg = "删除最后一个字段 [" + fieldNames.get(fieldCount - 1) + "] 继续尝试匹配";
                        //log.info(nextMsg);
                        matchingProcess.addMatchingDetail("规则" + ruleIndex + " " + nextMsg);
                    }
                }
            }

            //log.info("所有字段组合都无法匹配，路由规则ID: {} 匹配失败", rule.getId());
            matchingProcess.addMatchingDetail("规则" + ruleIndex + " 所有字段组合都无法匹配，匹配失败");
            return null;

        } catch (Exception e) {
            //log.error("路由规则ID: {} 匹配过程中发生异常: {}", rule.getId(), e.getMessage(), e);
            matchingProcess.addMatchingDetail("规则" + ruleIndex + " 匹配过程中发生异常: " + e.getMessage());
            return null;
        }
    }

    /**
     * 使用逐步删除字段的策略尝试匹配路由规则
     * 如果完整匹配失败，则逐步删除最后一个字段继续匹配，直到只剩一个字段仍无法匹配为止
     */
    private String tryMatchWithFieldReduction(RoutingRule rule, JsonNode taskDataJson) {
        if (rule.getFieldValues() == null || rule.getFieldValues().trim().isEmpty()) {
            //log.warn("路由规则ID: {} 的fieldValues为空，跳过匹配", rule.getId());
            return null;
        }

        if (taskDataJson == null) {
            //log.warn("任务数据为空，无法匹配路由规则ID: {}", rule.getId());
            return null;
        }

        try {
            // 解析路由规则的字段值
            JsonNode originalRuleFields = objectMapper.readTree(rule.getFieldValues());
            //log.info("开始匹配路由规则ID: {}，原始字段数量: {}", rule.getId(), originalRuleFields.size());

            // 将字段转换为列表，便于逐步删除
            java.util.List<String> fieldNames = new java.util.ArrayList<>();
            originalRuleFields.fieldNames().forEachRemaining(fieldNames::add);

            // 从完整字段开始，逐步删除最后一个字段进行匹配
            for (int fieldCount = fieldNames.size(); fieldCount >= 1; fieldCount--) {
                // 构建当前要匹配的字段集合
                java.util.List<String> currentFields = fieldNames.subList(0, fieldCount);

                //log.info("--- 尝试匹配 {} 个字段: {} ---", fieldCount, currentFields);

                // 检查当前字段集合是否匹配
                boolean allMatched = true;
                StringBuilder matchLog = new StringBuilder();
//                match//log.append("字段匹配详情:\n");

                for (String fieldName : currentFields) {
                    JsonNode ruleValue = originalRuleFields.get(fieldName);
                    JsonNode taskValue = taskDataJson.get(fieldName);

                    String ruleValueStr = ruleValue != null ? ruleValue.asText() : "null";
                    String taskValueStr = taskValue != null ? taskValue.asText() : "null";

                    boolean fieldMatched = taskValue != null && ruleValueStr.equals(taskValueStr);

//                    match//log.append(String.format("  字段[%s]: 规则值=%s, 任务值=%s, 匹配=%s\n",
//                            fieldName, ruleValueStr, taskValueStr, fieldMatched ? "✓" : "✗"));

                    if (!fieldMatched) {
                        allMatched = false;
                    }
                }

                //log.info(match//log.toString());

                if (allMatched) {
                    //log.info("*** 匹配成功！使用 {} 个字段匹配成功 ***", fieldCount);
                    if (fieldCount < fieldNames.size()) {
                        //log.info("注意：通过删除 {} 个字段后匹配成功，删除的字段: {}",
//                                fieldNames.size() - fieldCount,
//                                fieldNames.subList(fieldCount, fieldNames.size()));
                    }
                    return rule.getAssignedUsers();
                } else {
                    //log.info("使用 {} 个字段匹配失败", fieldCount);
                    if (fieldCount > 1) {
                        //log.info("删除最后一个字段 [{}] 继续尝试匹配", fieldNames.get(fieldCount - 1));
                    }
                }
            }

            //log.info("所有字段组合都无法匹配，路由规则ID: {} 匹配失败", rule.getId());
            return null;

        } catch (Exception e) {
            //log.error("路由规则ID: {} 匹配过程中发生异常: {}", rule.getId(), e.getMessage(), e);
            return null;
        }
    }

    /**
     * 检查路由规则是否匹配任务数据（保留原方法作为备用）
     */
    private boolean isRuleMatched(RoutingRule rule, JsonNode taskDataJson) {
        if (rule.getFieldValues() == null || rule.getFieldValues().trim().isEmpty()) {
            //log.warn("路由规则ID: {} 的fieldValues为空", rule.getId());
            return false;
        }

        if (taskDataJson == null) {
            //log.warn("任务数据为空，无法匹配路由规则");
            return false;
        }

        try {
            // 解析路由规则的字段值
            JsonNode ruleFieldsJson = objectMapper.readTree(rule.getFieldValues());

            // 检查每个字段是否匹配
            boolean matched = true;
            java.util.Iterator<String> iterator = ruleFieldsJson.fieldNames();
            while (iterator.hasNext()) {
                String fieldName = iterator.next();
                JsonNode ruleValue = ruleFieldsJson.get(fieldName);
                JsonNode taskValue = taskDataJson.get(fieldName);

                if (taskValue == null || !ruleValue.asText().equals(taskValue.asText())) {
                    matched = false;
                    break;
                }
            }

            return matched;

        } catch (Exception e) {
            //log.error("解析路由规则字段值失败: {}", e.getMessage(), e);
            return false;
        }
    }

    /**
     * 解析所有匹配到的审批人
     */
    private List<MultipleApprovalResultDTO.ApproverInfoDTO> parseAllApprovers(String routingApproverInfo, String defaultApproverInfo) {
        List<MultipleApprovalResultDTO.ApproverInfoDTO> approvers = new ArrayList<>();

        try {
            // 优先使用路由规则匹配的审批人
            String approverInfo = routingApproverInfo != null ? routingApproverInfo : defaultApproverInfo;

            if (approverInfo != null) {
                JsonNode approverJson = objectMapper.readTree(approverInfo);

                // 处理动态处理器格式: {"dynamicProcessors": {"config_0": [{"id": 16, "name": "李克勤", "authId": "001777881"}]}}
                if (approverJson.has("dynamicProcessors")) {
                    JsonNode dynamicProcessors = approverJson.get("dynamicProcessors");
                    // 遍历所有配置项
                    for (JsonNode configNode : dynamicProcessors) {
                        if (configNode.isArray()) {
                            for (JsonNode userNode : configNode) {
                                MultipleApprovalResultDTO.ApproverInfoDTO approver = parseApproverFromJson(userNode);
                                if (approver != null) {
                                    approvers.add(approver);
                                }
                            }
                        }
                    }
                }
                // 处理数组格式: [{"id": 1, "name": "张三", "authId": "auth001"}]
                else if (approverJson.isArray()) {
                    for (JsonNode userNode : approverJson) {
                        MultipleApprovalResultDTO.ApproverInfoDTO approver = parseApproverFromJson(userNode);
                        if (approver != null) {
                            approvers.add(approver);
                        }
                    }
                }
                // 处理对象格式: {"primaryUser": {"id": 1, "name": "张三", "authId": "auth001"}}
                else if (approverJson.has("primaryUser")) {
                    JsonNode primaryUser = approverJson.get("primaryUser");
                    MultipleApprovalResultDTO.ApproverInfoDTO approver = parseApproverFromJson(primaryUser);
                    if (approver != null) {
                        approvers.add(approver);
                    }
                }
            }
        } catch (Exception e) {
            //log.error("解析审批人信息失败: {}", e.getMessage(), e);
        }

        return approvers;
    }

    /**
     * 从JSON节点解析审批人信息
     */
    private MultipleApprovalResultDTO.ApproverInfoDTO parseApproverFromJson(JsonNode userNode) {
        if (userNode == null || !userNode.has("id")) {
            return null;
        }

        MultipleApprovalResultDTO.ApproverInfoDTO approver = new MultipleApprovalResultDTO.ApproverInfoDTO();
        approver.setUserId(userNode.get("id").asLong());
        approver.setUserName(userNode.has("name") ? userNode.get("name").asText() : "");
        approver.setUserAuthId(userNode.has("authId") ? userNode.get("authId").asText() : "");

        return approver;
    }

    /**
     * 根据负载均衡选择最合适的审批人
     * 选择负载最小的审批人
     */
    private MultipleApprovalResultDTO.ApproverInfoDTO selectApproverByLoadBalancing(List<MultipleApprovalResultDTO.ApproverInfoDTO> approvers) {
        if (approvers == null || approvers.isEmpty()) {
            return null;
        }

        if (approvers.size() == 1) {
            return approvers.get(0);
        }

        // 获取所有审批人的负载信息
        List<MultipleApprovalResultDTO.ApproverLoadInfoDTO> loadInfoList = getApproverLoadInfo(approvers);

        // 选择负载因子最小的审批人
        return loadInfoList.stream()
                .min((a, b) -> Double.compare(a.getLoadFactor(), b.getLoadFactor()))
                .map(loadInfo -> approvers.stream()
                        .filter(approver -> approver.getUserId().equals(loadInfo.getUserId()))
                        .findFirst()
                        .orElse(null))
                .orElse(approvers.get(0));
    }

    /**
     * 获取审批人的负载信息
     */
    private List<MultipleApprovalResultDTO.ApproverLoadInfoDTO> getApproverLoadInfo(List<MultipleApprovalResultDTO.ApproverInfoDTO> approvers) {
        List<MultipleApprovalResultDTO.ApproverLoadInfoDTO> loadInfoList = new ArrayList<>();

        for (MultipleApprovalResultDTO.ApproverInfoDTO approver : approvers) {
            MultipleApprovalResultDTO.ApproverLoadInfoDTO loadInfo = new MultipleApprovalResultDTO.ApproverLoadInfoDTO();
            loadInfo.setUserId(approver.getUserId());
            loadInfo.setUserName(approver.getUserName());

            try {
                // 查询该审批人的待处理任务数
                List<TaskApprovalStatus> pendingTasks = taskApprovalStatusMapper
                        .selectByApproverIdAndStatusProcessing(approver.getUserId());
                loadInfo.setPendingTasks(pendingTasks.size());

                // 查询该审批人的处理中任务数
                List<TaskApprovalStatus> processingTasks = taskApprovalStatusMapper
                        .selectByApproverIdAndStatusProcessing(approver.getUserId());
                loadInfo.setProcessingTasks(processingTasks.size());

                // 计算总活跃任务数
                int totalActiveTasks = loadInfo.getPendingTasks() + loadInfo.getProcessingTasks();
                loadInfo.setTotalActiveTasks(totalActiveTasks);

                // 计算负载因子（简单计算，可以根据需要调整算法）
                // 这里使用总活跃任务数作为负载因子
                loadInfo.setLoadFactor(totalActiveTasks);
            } catch (Exception e) {
                //log.error("获取审批人ID: {} 的负载信息失败: {}", approver.getUserId(), e.getMessage(), e);
                loadInfo.setPendingTasks(0);
                loadInfo.setProcessingTasks(0);
                loadInfo.setTotalActiveTasks(0);
                loadInfo.setLoadFactor(0.0);
            }

            loadInfoList.add(loadInfo);
        }

        return loadInfoList;
    }

    /**
     * 更新审批状态的审批人信息
     */
    private void updateApprovalStatusWithApprover(TaskApprovalStatus approvalStatus, String approverInfo) {
        //log.info("更新审批状态ID: {} 的审批人信息: {}", approvalStatus.getId(), approverInfo);

        try {
            // 解析审批人信息
            JsonNode approverJson = objectMapper.readTree(approverInfo);

            // 提取审批人ID和姓名
            Long approverId = null;
            String approverName = null;

            if (approverJson.has("primaryUser")) {
                // 处理对象格式: {"primaryUser": {"id": 1, "name": "张三", "authId": "auth001"}}
                JsonNode primaryUser = approverJson.get("primaryUser");
                if (primaryUser.has("id")) {
                    approverId = primaryUser.get("id").asLong();
                }
                if (primaryUser.has("name")) {
                    approverName = primaryUser.get("name").asText();
                }
            } else if (approverJson.has("dynamicProcessors")) {
                // 处理动态处理器格式: {"dynamicProcessors": {"config_0": [{"id": 16, "name": "李克勤", "authId": "001777881"}]}}
                JsonNode dynamicProcessors = approverJson.get("dynamicProcessors");
                // 遍历所有配置项
                for (JsonNode configNode : dynamicProcessors) {
                    if (configNode.isArray() && configNode.size() > 0) {
                        JsonNode firstUser = configNode.get(0);
                        if (firstUser.has("id")) {
                            approverId = firstUser.get("id").asLong();
                        }
                        if (firstUser.has("name")) {
                            approverName = firstUser.get("name").asText();
                        }
                        break; // 找到第一个有效用户就退出
                    }
                }
            } else if (approverJson.isArray() && approverJson.size() > 0) {
                // 处理数组格式: [{"id": 1, "name": "张三", "authId": "auth001"}]
                JsonNode firstUser = approverJson.get(0);
                if (firstUser.has("id")) {
                    approverId = firstUser.get("id").asLong();
                }
                if (firstUser.has("name")) {
                    approverName = firstUser.get("name").asText();
                }
            }

            // 如果仍然无法解析，记录错误信息
            if (approverId == null && approverName == null) {
                //log.error("无法解析审批人信息，格式不正确: {}", approverInfo);
            }

            // 更新审批状态
            if (approverId != null || approverName != null) {
                approvalStatus.setApproverId(approverId);
                approvalStatus.setApproverName(approverName);
                approvalStatus.setUpdatedAt(LocalDateTime.now());

                int updateResult = taskApprovalStatusMapper.updateById(approvalStatus);
                if (updateResult > 0) {
                    //log.info("成功更新审批状态ID: {} 的审批人信息 - ApproverId: {}, ApproverName: {}",
//                            approvalStatus.getId(), approverId, approverName);
                } else {
                    //log.error("更新审批状态失败，ID: {}", approvalStatus.getId());
                }
            } else {
                //log.warn("无法从审批人信息中提取有效的ID和姓名: {}", approverInfo);
            }

        } catch (Exception e) {
            //log.error("更新审批状态的审批人信息失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 更新审批状态的审批人信息
     */
    private void updateApprovalStatusWithSelectedApprover(TaskApprovalStatus approvalStatus,
                                                          MultipleApprovalResultDTO.ApproverInfoDTO selectedApprover) {
        //log.info("更新审批状态ID: {} 的审批人信息: ID={}, Name={}",
//                approvalStatus.getId(), selectedApprover.getUserId(), selectedApprover.getUserName());

        try {
            // 更新审批状态
            approvalStatus.setApproverId(selectedApprover.getUserId());
            approvalStatus.setApproverName(selectedApprover.getUserName());
            approvalStatus.setUpdatedAt(LocalDateTime.now());

            int updateResult = taskApprovalStatusMapper.updateById(approvalStatus);
            if (updateResult > 0) {
                //log.info("成功更新审批状态ID: {} 的审批人信息", approvalStatus.getId());
            } else {
                //log.error("更新审批状态失败，ID: {}", approvalStatus.getId());
            }
        } catch (Exception e) {
            //log.error("更新审批状态的审批人信息失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 将路由信息写入日志文件
     */
    private void writeRoutingInfoToFile(Long taskApprovalStatusId, TaskApprovalStatus approvalStatus,
                                        NewTask task, ProcessNode processNode, JsonNode taskDataJson,
                                        String defaultApproverInfo, String routingApproverInfo,
                                        String finalApproverInfo, MatchingProcess matchingProcess) {
        try {
            // 创建日志目录
            Path logDir = Paths.get(LOG_DIR);
            if (!Files.exists(logDir)) {
                Files.createDirectories(logDir);
            }

            // 生成日志文件名
            String fileName = LOG_FILE_PREFIX + LocalDateTime.now().format(FILE_DATE_FORMAT) + ".log";
            Path logFile = logDir.resolve(fileName);

            // 写入日志信息
            try (PrintWriter writer = new PrintWriter(new FileWriter(logFile.toFile(), true))) {
                writer.println("任务路由信息记录 - " + LocalDateTime.now().format(LOG_TIME_FORMAT));

                // 基本信息
                writer.println("【基本信息】");
                writer.println("任务审批状态ID: " + taskApprovalStatusId);
                writer.println("任务ID: " + (approvalStatus != null ? approvalStatus.getTaskId() : "N/A"));
                writer.println("流程ID: " + (approvalStatus != null ? approvalStatus.getFlowId() : "N/A"));
                writer.println("节点ID: " + (approvalStatus != null ? approvalStatus.getNodeId() : "N/A"));
                writer.println("节点顺序: " + (approvalStatus != null ? approvalStatus.getNodeOrder() : "N/A"));
                writer.println();

                // 任务详细数据
                writer.println("【任务详细数据】");
                if (task != null) {
                    writer.println("业务唯一ID: " + task.getBizUniqueId());
                    writer.println("数据源ID: " + task.getDataSourceId());
                    writer.println("原始数据长度: " + (task.getRawData() != null ? task.getRawData().length() : 0));
                    if (taskDataJson != null) {
                        writer.println("解析后的任务数据:");
                        writer.println(taskDataJson.toPrettyString());
                    } else {
                        writer.println("任务数据解析失败或为空");
                    }
                } else {
                    writer.println("任务信息不存在");
                }
                writer.println();

                // 流程节点信息
                writer.println("【流程节点信息】");
                if (processNode != null) {
                    writer.println("节点名称: " + processNode.getNodeName());
                    writer.println("部门: " + processNode.getDepartment());
                    writer.println("角色: " + processNode.getRole());
                    writer.println("部门ID: " + processNode.getDepartmentId());
                    writer.println("角色ID: " + processNode.getRoleId());
                } else {
                    writer.println("流程节点信息不存在");
                }
                writer.println();

                // 默认处理人信息
                writer.println("【默认处理人信息】");
                writer.println(defaultApproverInfo != null ? defaultApproverInfo : "未找到默认处理人");
                writer.println();

                // 路由规则匹配信息
                writer.println("【路由规则匹配信息】");
                if (matchingProcess != null) {
                    writer.println("路由规则列表:");
                    for (String rule : matchingProcess.getRoutingRules()) {
                        writer.println("  " + rule);
                    }
                    writer.println();

                    writer.println("匹配过程详情:");
                    for (String detail : matchingProcess.getMatchingDetails()) {
                        writer.println("  " + detail);
                    }
                    writer.println();

                    writer.println("匹配结果: " + (matchingProcess.getFinalResult() != null ? matchingProcess.getFinalResult() : "无匹配结果"));
                    writer.println("匹配原因: " + (matchingProcess.getReason() != null ? matchingProcess.getReason() : "无原因说明"));
                } else {
                    writer.println(routingApproverInfo != null ? routingApproverInfo : "未找到匹配的路由规则");
                }
                writer.println();

                // 最终审批人信息
                writer.println("【最终审批人信息】");
                writer.println(finalApproverInfo != null ? finalApproverInfo : "未确定审批人");
                writer.println();
                writer.println();

                //log.info("路由信息已写入日志文件: {}", logFile.toString());
            }

        } catch (IOException e) {
            //log.error("写入路由日志文件失败: {}", e.getMessage(), e);
        }
    }
}